package cc.parkhome.common.ports.web.msg;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 发送http请求
 *
 * @author liuxq
 */
public class HttpClientUtil {
    public static final Log logger = LogFactory.getLog("httpclient");

    /**
     * 向指定URL发送GET方法的请求
     * 返回响应流的方法
     *
     * @param url    发送请求的URL
     * @param params 请求参数
     * @return 流 所代表远程资源的响应结果
     */
    public static InputStream sendGetReturnStream(String url, HashMap<String, String> params) {
        InputStream result = null;

        try {
            /**组装参数**/
            String param = parseParams(params);
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            /**打开和URL之间的连接**/
            URLConnection connection = realUrl.openConnection();
            /**设置通用的请求属性**/
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setReadTimeout(30000);
            /**建立实际的连接**/
            connection.connect();
            /**定义 BufferedReader输入流来读取URL的响应**/
            result = connection.getInputStream();
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {/**使用finally块来关闭输入流**/
        }
        return result;
    }

    public static String httpReader(String url, String code) throws Exception {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
                "UTF-8");
        GetMethod method = new GetMethod(url);

        String result = null;
        try {
            client.executeMethod(method);
            int status = method.getStatusCode();
            if (status == HttpStatus.SC_OK) {
                result = method.getResponseBodyAsString();
            } else {
                logger.info("Method failed: " + method.getStatusLine());
            }
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
            method = null;
            client = null;
        }
        return result;
    }

    public static String httpPost(String url, Map<String, String> paramMap,
                                  String code) {
        logger.info("GetPage:" + url);
        String content = null;
        if (url == null || url.trim().length() == 0)
            return null;
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter(
                HttpMethodParams.HTTP_CONTENT_CHARSET, code);
        PostMethod post = new PostMethod(url);
        post.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=utf-8");
        NameValuePair[] param = null;
        if (paramMap != null) {
            param = new NameValuePair[paramMap.size()];
            Set entrySet = paramMap.entrySet();
            int i = 0;
            for (Iterator<Map.Entry<String, String>> iter = entrySet.iterator(); iter
                    .hasNext(); ) {
                Map.Entry<String, String> me = iter.next();
                param[i] = new NameValuePair(me.getKey(), me.getValue());
                i++;
            }
            post.setRequestBody(param);
        }

        try {
            httpClient.executeMethod(post);
            logger.info(post.getStatusLine());
            content = post.getResponseBodyAsString();
            content = new String(post.getResponseBody(), code);

        } catch (Exception e) {
            logger.info("time out");
            e.printStackTrace();
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
            post = null;
            httpClient = null;
        }
        return content;
    }

    public static int httpPostNoResultContent(String url,
                                              Map<String, String> paramMap, String code) {
        logger.info("GetPage:" + url);
        int postState = 500;
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter(
                HttpMethodParams.HTTP_CONTENT_CHARSET, code);
        PostMethod post = new PostMethod(url);
        post.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=utf-8");
        NameValuePair[] param = null;
        if (paramMap != null) {
            param = new NameValuePair[paramMap.size()];
            Set entrySet = paramMap.entrySet();
            int i = 0;
            for (Iterator<Map.Entry<String, String>> iter = entrySet.iterator(); iter
                    .hasNext(); ) {
                Map.Entry<String, String> me = iter.next();
                param[i] = new NameValuePair(me.getKey(), me.getValue());
                i++;
            }
            post.setRequestBody(param);
        }

        try {
            httpClient.executeMethod(post);
            logger.info(post.getStatusLine());
            postState = post.getStatusCode();

        } catch (Exception e) {
            logger.info("time out");
            e.printStackTrace();
        } finally {
            if (post != null)
                post.releaseConnection();
            post = null;
            httpClient = null;
        }
        return postState;
    }

    public static String httpPost(String url, Map<String, String> params) {
        return httpPost(url, params, "utf-8");
    }

    public static String sendMsg(String mobile, String msg) {
        Map paramMap = new HashMap();
        paramMap.put("sn", "SDK-BBX-010-24579");
        paramMap.put("pwd", "A973C7165F0548378DCE83BF8984BB92");
        paramMap.put("mobile", mobile);
        paramMap.put("content", msg);
        paramMap.put("rrid", "666666");
        String rs = httpPost("http://sdk2.entinfo.cn:8061/mdsmssend.ashx",
                paramMap);
        return rs;
    }

    /**
     * 将HashMap参数组装成字符串
     *
     * @param map
     * @return
     */
    private static String parseParams(HashMap<String, String> map) {
        StringBuffer sb = new StringBuffer();
        if (map != null) {
            for (Map.Entry<String, String> e : map.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.substring(0, sb.length() - 1);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
/*	String msg = "{\"number\":\"陈大涛\",\"age\":\"26\",\"sex\":\"男\"}";
    Map paramMap = new HashMap();
	paramMap.put("number", "陈大涛");
	String rs = httpPost("http://127.0.0.1:8080/mycar/api/car/insertToUserCar.do?appId=888888",
		paramMap);
	System.out.println("OK" + rs);*/
        System.out.println(sendMsg("17777786854", "你的验证码是4862，20分钟内有效,parkhome【企业选址】"));
    }

}
